<template>
	<view class="reg-page">
		<view class="ball-team-info" v-if="teamObj.nm&&teamObj.rpbNm">
			<view>所属球队：{{teamObj.nm}}</view>
			<view>级别：{{teamObj.typ == 0 ? '公开组':'职工组'}}</view>
			<view>管理员：{{teamObj.rpbNm}}</view>
		</view>
		<view style="padding: 0 10px;margin-top: 10px;">
			<view class="form-sty">
				<text class="input-title">球员头像</text>
				<uni-file-picker :disabled="btnFla" class="img-sty" :auto-upload="false" limit="1" mode="grid"
					:disablePreview="false" file-mediatype="image" :sizeType="sizeType" @fail="imgFail"
					@progress="imgProgress" ref="portrait" v-model="portrait" @delete="(e) => {delImg(e, 'portrait')}"
					@select="(e)=>{imgSelect(e,'portrait')}" @success="(e)=> {imgSuccess(e,'portrait')}">
				</uni-file-picker>
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">姓名</text>
				<input v-if="!formData._id || formData.userStatus == 2" class="input-sty" type="text" v-model="formData.userNm" placeholder="姓名"
					:disabled="btnFla" :maxlength="4">
				<text v-else class="input-sty is-disabled">{{formData.userNm}}</text>
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">手机号</text>
				<input v-if="!formData._id || formData.userStatus == 2" class="input-sty" type="text" v-model="formData.phone" :maxlength="11"
					placeholder="手机号" :disabled="btnFla">
				<text v-else class="input-sty is-disabled">{{formData.phone}}</text>
			</view>
			<view class="form-sty">
				<text class="input-title">性别</text>
				<!-- 0否，1是 -->
				<uni-data-checkbox v-model="formData.gender" :localdata="items" :disabled="btnFla" />
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">是否是外援</text>
				<!-- 0否，1是 -->
				<uni-data-checkbox v-model="formData.assistance" :localdata="isAssistList" :disabled="btnFla" />
			</view>
<!-- 			<view class="form-sty">
				<text class="input-title">邮箱</text>
				<input class="input-sty" type="text" v-model="formData.email" placeholder="邮箱" :disabled="btnFla">
			</view> -->
			<view class="form-sty">
				<text class="input-title bi-shu-sty">球衣号码</text>
				<input class="input-sty" type="text" v-model="formData.jerseyNum" :maxlength="2" placeholder="球衣号码"
					:disabled="btnFla">
			</view>
			<view class="form-sty">
				<text class="input-title">身高</text>
				<input class="input-sty" type="text" v-model="formData.height" :maxlength="3" placeholder="身高"
					:disabled="btnFla">
			</view>
			<view class="form-sty">
				<text class="input-title">体重</text>
				<input class="input-sty" type="text" v-model="formData.weight" :maxlength="3" placeholder="体重"
					:disabled="btnFla">
			</view>
			<view class="form-sty">
				以下信息三选一
			</view>
			<view class="form-sty">
				<view @click="selectInfo(0)" class="info-sty" :style="infoFla == 0 ? 'color: #fc993b;':''">社保</view>
				<view @click="selectInfo(1)" class="info-sty" :style="infoFla == 1 ? 'color: #fc993b;':''">户籍证明</view>
				<view @click="selectInfo(2)" class="info-sty" :style="infoFla == 2 ? 'color: #fc993b;':''">房产</view>
			</view>
<!-- 			<view class="form-sty" v-show="infoFla == 0">
				<text class="input-title bi-shu-sty">高新区户籍</text>
				<uni-data-checkbox v-model="formData.isLocal" :localdata="teamType" :disabled="formData._id && formData.userStatus != 2" />
			</view> -->
			<view v-show="infoFla == 0" style="color:red;font-size: 12px;margin-top: 10px;">注：连续一年社保证明</view>
			<view class="form-sty" v-show="infoFla == 0">
				<text class="input-title bi-shu-sty">社保号</text>
				<input class="input-sty" type="text" v-model="formData.socialNo" :maxlength="18" placeholder="社保号"
					:disabled="formData._id && formData.userStatus != 2">
			</view>
			<view class="form-sty" v-show="infoFla == 0">
				<text class="input-title bi-shu-sty">社保截图</text>
				<uni-file-picker v-if="!formData._id || formData.userStatus == 2" :disabled="formData._id&& formData.userStatus != 2" class="img-sty" :auto-upload="false" limit="1" mode="grid"
					:disablePreview="false" file-mediatype="image" :sizeType="sizeType" @fail="imgFail"
					@progress="imgProgress" ref="socialImg" v-model="socialImg"
					@delete="(e) => {delImg(e, 'socialImg')}" @select="(e)=>{imgSelect(e,'socialImg')}"
					@success="(e)=> {imgSuccess(e,'socialImg')}">
				</uni-file-picker>
				<img v-else :src="socialImg[0].url" alt="" class="img-edit-no-sty">
			</view>
			<view class="form-sty" v-show="infoFla == 1">
				<text class="input-title bi-shu-sty">证件号</text>
				<input class="input-sty" type="text" v-model="formData.identityCardNo" :maxlength="18" placeholder="证件号"
					:disabled="formData._id && formData.userStatus != 2">
			</view>
			<view class="form-sty" v-show="infoFla == 1">
				<text class="input-title bi-shu-sty">证明一</text>
				<uni-file-picker v-if="!formData._id || formData.userStatus == 2" :disabled="formData._id&& formData.userStatus != 2" class="img-sty" :auto-upload="false" limit="1" mode="grid"
					:disablePreview="false" file-mediatype="image" :sizeType="sizeType" @fail="imgFail"
					@progress="imgProgress" ref="identityCardImg" v-model="identityCardImg"
					@delete="(e) => {delImg(e, 'identityCardImg')}" @select="(e)=>{imgSelect(e,'identityCardImg')}"
					@success="(e)=> {imgSuccess(e,'identityCardImg')}">
				</uni-file-picker>
				<img v-else :src="identityCardImg[0].url" alt="" class="img-edit-no-sty">
			</view>
			<view class="form-sty" v-show="infoFla == 1">
				<text class="input-title bi-shu-sty">证明二</text>
				<uni-file-picker v-if="!formData._id || formData.userStatus == 2" :disabled="formData._id&& formData.userStatus != 2" class="img-sty" :auto-upload="false" limit="1" mode="grid"
					:disablePreview="false" file-mediatype="image" :sizeType="sizeType" @fail="imgFail"
					@progress="imgProgress" ref="identityCardImgB" v-model="identityCardImgB"
					@delete="(e) => {delImg(e, 'identityCardImgB')}" @select="(e)=>{imgSelect(e,'identityCardImgB')}"
					@success="(e)=> {imgSuccess(e,'identityCardImgB')}">
				</uni-file-picker>
				<img v-else :src="identityCardImgB[0].url" alt="" class="img-edit-no-sty">
			</view>
			<view class="form-sty" v-show="infoFla == 2">
				<text class="input-title bi-shu-sty">高新区房产</text>
				<!-- 0否，1是 -->
				<uni-data-checkbox v-model="formData.isLocalProperty" :localdata="teamType" :disabled="formData._id && formData.userStatus != 2" />
			</view>
			<view class="form-sty" v-show="infoFla == 2">
				<text class="input-title bi-shu-sty">房产证图片</text>
				<uni-file-picker v-if="!formData._id || formData.userStatus == 2" :disabled="formData._id&& formData.userStatus != 2" class="img-sty" :auto-upload="false" limit="1" mode="grid"
					:disablePreview="false" file-mediatype="image" :sizeType="sizeType" @fail="imgFail"
					@progress="imgProgress" ref="propertyImg" v-model="propertyImg"
					@delete="(e) => {delImg(e, 'propertyImg')}" @select="(e)=>{imgSelect(e,'propertyImg')}"
					@success="(e)=> {imgSuccess(e,'propertyImg')}">
				</uni-file-picker>
				<img v-else :src="propertyImg[0].url" alt="" class="img-edit-no-sty">
			</view>
			<view v-if="btnFla" style="margin: 35px auto;padding-bottom: 50px;text-align: center;">
				<view class="btn-area" @click="editBtn" style="display: inline-block;">
					<view class="btn-sty" style="background: #fc993b;color:#fff;">编辑</view>
				</view>
			</view>
			<view style="display: flex;margin-top: 35px;padding-bottom: 50px;" v-else>
				<view class="btn-area" @click="backPage">
					<view class="btn-sty">取消</view>
				</view>
				<view class="btn-area" @click="confirmBtn">
					<view class="btn-sty" style="background: #fc993b;color:#fff;">确认</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		cheackUser,
		getImageList,
		checkFontRule,
		verifyForm
	} from '@/utils/baseFn.js';
	const db = uniCloud.database()
	const items = [{
			value: '0',
			text: '女'
		},
		{
			value: '1',
			text: '男'
		}
	]
	const teamType = [{
			value: '0',
			text: '否'
		},
		{
			value: '1',
			text: '是'
		}

	]
	const isAssistList = [{
			value: '0',
			text: '否'
		},
		{
			value: '1',
			text: '是'
		}
	]
	export default {
		data() {
			return {
				baseData: {},
				formData: {
					userNm: '',
					userType: '',
					userStatus: '',
					email: '',
					classIds: '',
					ballTeamNm: '',
					ballTeamName: '',
					ballTeamType: '',
					companyAddress: '',
					portrait: '',
					phone: '',
					assistance: '',
					jerseyNum: '',
					height: '',
					weight: '',
					gender: '',
					socialNo: '',
					socialImg: '',
					isLocal: '',
					identityCardNo: '',
					identityCardImg: '',
					identityCardImgB: '',
					isLocalProperty: '',
					propertyImg: '',
					opinion: '',
					originalTeam: '',
					deleted_at: null,
					created_date: null,
					updated_date: null,
					created_by: null
				},
				teamObj: {},
				portrait: [],
				socialImg: [],
				identityCardImg: [],
				identityCardImgB: [],
				propertyImg: [],
				sizeType: ['original', 'compressed'],
				items: items,
				teamType: teamType,
				isAssistList: isAssistList,
				btnFla: false,
				infoFla: 0,
				tempId: null
			}
		},
		onLoad(e) {
			const _this = this
			this.teamObj = JSON.parse(e.parm)
			// if (this.teamObj.fx == 1) { // 分享过来的需要跳转确认书页面
			// 	uni.navigateTo({
			// 		url: `./register/ballTeamSelect?parm=${e.parm}`
			// 	});
			// 	return
			// }
			const setFormData = function(list) {
				_this.formData = list
				_this.formData.ballTeamNm = _this.teamObj.id || _this.teamObj.ballTeamNm
				_this.formData.ballTeamType = _this.teamObj.typ || _this.formData.ballTeamType
				if (_this.formData.portrait) {
					_this['portrait'] = getImageList(list.portrait, _this
						.$baseImgUrl)
				}
				if (_this.formData.socialImg) {
					_this['socialImg'] = getImageList(list.socialImg, _this
						.$baseImgUrl)
				}
				if (_this.formData.identityCardImg) {
					_this['identityCardImg'] = getImageList(list.identityCardImg,
						_this.$baseImgUrl)
				}
				if (_this.formData.identityCardImgB) {
					_this['identityCardImgB'] = getImageList(list.identityCardImgB,
						_this.$baseImgUrl)
				}
				if (_this.formData.propertyImg) {
					_this['propertyImg'] = getImageList(list.propertyImg, _this
						.$baseImgUrl)
				}
			}
			if (this.teamObj.userStatus == 2) {
				let text
				setFormData(this.teamObj)
				if (this.teamObj.opinion) {
					text = JSON.parse(this.teamObj.opinion)
				}
				uni.showModal({
					content: `驳回原因：${text[0].op}`,
					showCancel: false
				})
			} else {
				this.formData.ballTeamNm = this.teamObj.id
				this.formData.ballTeamName = this.teamObj.nm
				this.formData.ballTeamType = this.teamObj.typ
				uni.getStorage({
					key: 'userInfo',
					success: function(res) {
						if (res.data) {
							_this.baseData = res.data
							if (_this.teamObj.nm && _this.teamObj.rpbNm) {
								uni.showModal({
									content: '是否将本人基础信息映射到球员表单中？',
									success: function(res) {
										if (res.confirm) {
											let list = {..._this.baseData}
											_this.tempId = list._id
											list._id = ''
											setFormData(list)
										}
										// else {
										// 	_this.formData.ballTeamNm = _this.teamObj.id
										// 	_this.formData.ballTeamType = _this.teamObj.typ
										// }
									},
									fail: function(res) {}
								})
							} else {
								setFormData(_this.baseData)
								_this.btnFla = true
							}
						}
						//  else {
						// 	_this.formData.ballTeamNm = _this.teamObj.id
						// 	_this.formData.ballTeamType = _this.teamObj.typ
						// }
					},
					fail: function(res) {}
				})
			}
		},
		created() {},
		mounted() {},
		methods: {
			selectInfo (fla) {
				this.infoFla = fla
			},
			// 手动上传
			upload(ref) {
				// 插件上传
				this.$refs[ref].upload()
			},
			// 获取上传状态
			imgSelect(e, ref, index = 0) {
				console.log('选择文件：', e)
				uni.showLoading({
					title: '图片上传中。。。',
					mask: true
				});
				e.tempFiles.map(item => {
					if (`jpg,jpeg,png`.indexOf(item.extname) > -1) {
						if (item.size > 522183) {
							this.compress(item, index, ref);
						} else {
							this.upload(ref)
						}
					} else {
						this.upload(ref)
					}
				})
			},
			// 删除附件
			delImg(e, ref) {
				const _this = this
				let str = '删除后该图片将无法在页面展示，请谨慎删除！'
				let tt = `删除图片？`
				if (this.btnFla) {
					str = '点击编辑按钮后方可修改！'
					tt = '不能删除！'
				}
				uni.showModal({
					title: tt,
					content: str,
					success: async (res) => {
						if (res.confirm) {
							if (_this.btnFla) {
								const file = _this.formData[ref].split(',')
								_this[ref] = [{
									fileID: `${_this.$baseImgUrl}${file[0]}`,
									url: `${_this.$baseImgUrl}${file[0]}`,
									name: file[1]
								}]
								return
							} else {
								const annexFn = uniCloud.importObject('annex-del-fn')
								await annexFn.delFileFn([e.tempFile.fileID])
								_this.formData[ref] = ''
							}

						} else {
							const file = this.formData[ref].split(',')
							_this[ref] = [{
								fileID: `${_this.$baseImgUrl}${file[0]}`,
								url: `${_this.$baseImgUrl}${file[0]}`,
								name: file[1]
							}]
						}
					},
					fail: () => {
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						})
					}
				})
			},
			// 获取上传进度
			imgProgress(e) {
				console.log('上传进度：', e)
				if (e.progress == 100) {
					uni.hideLoading();
				}
			},
			// 上传成功
			imgSuccess(e, ref) {
				const url = e.tempFilePaths[0].split('/')
				this.formData[ref] = `${url[url.length - 1]},${e.tempFiles[0].name}`
				console.log('上传成功', e, this.formData[ref])
			},
			// 上传失败
			imgFail(e) {
				console.log('上传失败：', e)
			},
			compress(r, index, ref) { // 图片压缩
				var that = this;
				const num = r.size > 2251836 ? 3 : r.size < 1225836 ? 34 : 8
				console.log(r.size, '>522183原图大小', num, '压缩比例');
				if (r.size) {
					wx.compressImage({
						src: r.path,
						quality: num, // 0-100,越高却清晰
						success(res) {
							that.SizeImg(r, res, index, ref, num);
						}
					})
				}
			},
			SizeImg(r, res, n, ref, num) { // 查询图片大小
				let that = this;
				const arr = []
				wx.getFileInfo({ //查询压缩后的图片大小
					filePath: res.tempFilePath,
					success(ys) {
						let h = that.$refs[ref].filesList[n].image.height * ((100 - num) / 100)
						let w = that.$refs[ref].filesList[n].image.width * ((100 - num) / 100)
						console.log('压缩后的文件大小：' + ys.size);
						console.log('压缩后的临时路径：' + res.tempFilePath);
						that.$refs[ref].filesList[n].path = res.tempFilePath
						that.$refs[ref].filesList[n].size = ys.size
						that.$refs[ref].filesList[n].url = res.tempFilePath
						that.$refs[ref].filesList[n].image = {
							height: h,
							location: res.tempFilePath,
							width: w
						}
						that.$refs[ref].filesList[n].width = w
						that.$refs[ref].filesList[n].height = h
						that.$refs[ref].filesList[n].location = res.tempFilePath
						that.upload(ref)
					}
				})
			},
			editBtn() {
				this.btnFla = false
			},
			backPage() {
				uni.navigateBack({
					delta: 1
				})
			},
			restBtn() {
				const _this = this
				const rest = function() {
					_this.formData.email = ''
					_this.formData.companyAddress = ''
					_this.formData.portrait = ''
					_this.formData.jerseyNum = ''
					_this.formData.height = ''
					_this.formData.weight = ''
					_this.formData.assistance = ''
					_this.formData.gender = ''
					_this.formData.socialNo = ''
					_this.formData.socialImg = ''
					_this.formData.isLocal = ''
					_this.formData.identityCardNo = ''
					_this.formData.identityCardImg = ''
					_this.formData.identityCardImgB = ''
					_this.formData.isLocalProperty = ''
					_this.formData.propertyImg = ''
					const annexFn = uniCloud.importObject('annex-del-fn')
					annexFn.delFileFn([_this.propertyImg[0].fileID, _this.identityCardImg[0].fileID, _this.portrait[0]
						.fileID, _this.socialImg[0].fileID
					])
					_this.propertyImg = []
					_this.identityCardImg = []
					_this.identityCardImgB = []
					_this.portrait = []
					_this.socialImg = []
				}
				if (this.tempId) {
					rest()
				} else {
					this.formData.userNm = ''
					this.formData.phone = ''
					rest()
				}
			},
			cheackInfo (res) {
				let arr;
				let fla = true
				const fn = function (r, a) {
					let f = true
					for (let k in r) {
						if (!r[k]) {
							const o = a.find(item => item.k == k)
							if (o) {
								uni.showModal({
									content: `${o.v}不能为空请补充！`,
									showCancel: false
								})
								f = false
							}
						}
					}
					return f
				}
				if (this.infoFla == 0) { // 社保
					arr = [
						// {
						// 	k: 'isLocal',
						// 	v: '高新区户籍'
						// },
						{
							k: 'socialNo',
							v: '社保号'
						},
						{
							k: 'socialImg',
							v: '社保截图'
						},
					]
					fla = fn(res, arr)
				}
				if (this.infoFla == 1) { // 证件
					arr = [
						{
							k: 'identityCardNo',
							v: '证件号'
						},
						{
							k: 'identityCardImg',
							v: '证件照头像面'
						},
						{
							k: 'identityCardImgB',
							v: '证件照国徽面'
						},
					]
					fla = fn(res, arr)
				}
				if (this.infoFla == 2) { // 房产
					arr = [
						{
							k: 'isLocalProperty',
							v: '是否有高新房产'
						},
						{
							k: 'propertyImg',
							v: '房产证照片'
						}
					]
					fla = fn(res, arr)
				}
				return fla
			},
			confirmBtn() {
				const _this = this
				if (!verifyForm(this.formData)) return
				if (!checkFontRule(this.formData.phone, '0')) return
				if (!this.cheackInfo(this.formData)) return
				if (this.formData.identityCardNo) {
					if (!checkFontRule(this.formData.identityCardNo, '1')) return
				}
				if (this.formData.email) {
					if (!checkFontRule(this.formData.email, '2')) return
				}
				uni.showLoading({
					mask: true
				});
				if (this.tempId) {
					const id = this.tempId
					const parm = {}
					for (let k in this.formData) {
						if (k !== '_id') {
							parm[k] = this.formData[k]
						}
					}
					return db.collection('user-MGMT').doc(id).update(parm).then((res) => {
						uni.showToast({
							title: '修改成功'
						})
						uni.setStorage({
							key: 'userInfo',
							data: _this.formData || {},
							success: function() {
								console.log('success');
							}
						})
						if (this.teamObj.userStatus == 2) {
							uni.removeStorage({
								key: 'userInfo',
								success: function() {
									setTimeout(() => {
										uni.switchTab({
											url: '../home/home'
										});
									}, 1228)
								}
							})
						} else {
							setTimeout(() => uni.navigateBack(), 1228)
						}
						uni.hideLoading();
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
						uni.hideLoading();
					})
				} else {
					const parm = {
						phone: this.formData.phone
						// identityCardNo: this.formData.identityCardNo
					}
					cheackUser(parm, 'reg').then(res => {
						console.log(res)
						if (!res.fla) {
							const parm = {
								userStatus: '0', // 用户状态 0待审批，1通过，2退回
								userType: '1', // 0 会员 1 球员 2负责人
								deleted_at: null,
								created_date: new Date().getTime(),
								updated_date: null,
								created_by: this.formData.userNm
							}
							const value = {
								...this.formData,
								...parm
							}
							console.log(value)
							value.password = value.phone.substring(5,11)
							return db.collection('user-MGMT').add(value).then((res) => {
								uni.showToast({
									title: '新增成功'
								})
								setTimeout(() => uni.navigateBack(), 1228)
								uni.hideLoading();
							}).catch((err) => {
								uni.showModal({
									content: err.message || '请求服务失败',
									showCancel: false
								})
								uni.hideLoading();
							})
						} else {
							uni.hideLoading();
						}
					})
				}
			}
		}
	}
</script>

<style>
	.reg-page {}

	.form-sty .uni-file-picker {
		display: inline-block;
		width: 50%;
	}

	.reg-page .uni-data-checklist {
		width: 50%;
		display: inline-block;
	}

	.input-title {
		width: 43%;
		display: inline-block;
		vertical-align: top;
	}

	.img-sty {
		width: 60%;
		height: 68px;
		display: inline-block;
	}

	.input-sty {
		width: 57%;
		display: inline-block;
		vertical-align: middle;
	}

	.is-disabled {
		width: 50%;
		color: #888;
	}

	.form-sty {
		width: 100%;
		height: 70px;
		border-bottom: 1px solid #dcdfe6;
		line-height: 70px;
		padding: 0 5px;
	}

	.btn-area {
		width: 150px;
		text-align: center;
		flex: 1;
	}

	.btn-sty {
		width: 150px;
		height: 38px;
		color: #fc993b;
		background: #ffffff;
		border: 1px solid #fc993b;
		border-radius: 20px;
		line-height: 38px;
		margin: 0 auto;
	}

	.ball-team-info {
		display: flex;
		margin: 20px 0;
		justify-content: space-around;
		font-size: 30rpx;
		font-weight: 500;
	}

	.bi-shu-sty::before {
		content: '*';
		position: relative;
		top: 0;
		left: 0;
		color: red;
	}
	.img-edit-no-sty {
		width: 70px;height: 70px;
	}
	.info-sty {
		width: 33%;display:inline-block;text-align: center;
	}
</style>
<style lang="scss">
</style>
